import { Directive, ElementRef, Input } from '@angular/core';
//Controls
import { AmChartsService } from "@amcharts/amcharts3-angular";
import { UtilsService } from '../../services/utils.service';

@Directive({
    selector: '[barChart]',
    providers: [UtilsService]
})
export class BarChartDirective {
    private chart: any;
    private _chartData: any[] = [];

    @Input() chartID: string;
    @Input() showCategoryNames: boolean = true;

    @Input() set chartData(value: any[]) {
        if (value) {
            this._chartData = value;

            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.chart.dataProvider = this._chartData;
                });
            }
        }
    }

    constructor(private el: ElementRef, private AmCharts: AmChartsService) { }

    ngOnInit() {
        this.chart = this.AmCharts.makeChart(this.chartID, {
            type: "serial",
            rotate: true,
            autoMarginOffset: 0,
            //autoMargins: false,
            marginTop: 0,
            marginLeft: 0,
            marginBottom: 0,
            marginRight: 10,
            columnWidth: 0.6,
            dataProvider: this._chartData,
            addClassNames: true,
            graphs: [{
                colorField: "color",
                fillAlphas: 0.8,
                lineColor: "#1D6094",
                type: "column",
                valueField: "value",
                labelText: "[[label]]"
            }],
            balloon: {
                enabled: false
            },
            categoryField: "name",
            categoryAxis: {
                classNameField: 'className',
                tickLength: 0,
                gridAlpha: 0,
                labelFunction: function (valueText, serialDataItem, categoryAxis) {
                    return valueText + " " + UtilsService.roundUp(serialDataItem.dataContext.labelValue);
                },
                labelsEnabled: this.showCategoryNames
            },
            valueAxes: [{
                axisAlpha: 0,
                gridAlpha: 0,
                minimum: 0,
                maximum: 100, //so it displays the graph for max value (100)
                labelsEnabled: false
            }]
        });
    }

    ngOnDestroy() {
        this.AmCharts.destroyChart(this.chart);
    }
}